package com.wangjw.tuling.netty.basic;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Created by wangjianwen on 2018/12/5.
 */
public class EchoServer {

    public static void main(String[] args) throws Exception {
        new EchoServer().bing(8080);
    }

    private void bing(int port) throws Exception {
        // 第一步：
        // 配置服务端的NIO线程组
        // 主线程组, 用于接受客户端的连接，但是不做任何具体业务处理，像老板一样，负责接待客户，不具体服务客户
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);

        // 工作线程组, 老板线程组会把任务丢给他，让手下线程组去做任务，服务客户
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            // 类ServerBootstrap用于配置Server相关参数，并启动Server
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            // 链式调用
            // 配置parentGroup和childGroup
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class) // 配置Server通道
                    .childHandler(new ChildChannelHandler()); // 配置通道的ChannelPipeline

            // 绑定端口，并启动server，同时设置启动方式为同步
            ChannelFuture future = serverBootstrap.bind(port).sync();
            System.out.println(EchoServer.class.getName() + " 启动成功，在地址 " + future.channel().localAddress() + " 上等待客户请求......");

            // 等待服务端监听端口关闭
            future.channel().closeFuture().sync();
        } finally {
            // 优雅退出，释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {

        @Override
        protected void initChannel(SocketChannel channel) throws Exception {
            channel.pipeline().addLast(new EchoServerHandler());
        }
    }
}
